﻿<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Book extends MY_Controller {

	public function __construct() {
		parent::__construct();

		//Load models to use some functions in it
		$this->load->model('model_books');

		//Load helpers to use some functions in it
		$this->load->helper('bookaccess');

		$this->load->helper('file');
	}

	public function index() {
		redirect(base_url());
	}
	

	public function category($catId = null) {
        if ($catId == null) redirect(base_url());


		$this->load->model('model_categories');
		$arr = $this->model_categories->catBooks($catId);

		$data['nameCat'] = $this->model_categories->getCategoryName($catId);

		$list = array();
		foreach ($arr as $document) {
			$book['id'] = $document['id_document'];
			$book['title'] = $document['name_document'];
			$book['cat'] = $document['name_cat'];
			$book['uploader'] = $document['username'];
			$book['author'] = $document['author'];
			if($book['author'] == '') $book['author'] = 'Chưa rõ';
			
			$linkcover = getCover($document['id_document']);
			$book['cover'] = $linkcover;

			array_push($list, $book);
		}
		$data['list'] = $list;
		
		//Get menu
        $data['template']['menu'] = createMenu();
        if($this->is_login())
        	$data['template']['user'] = $this->session->userdata('username');

		$this->load->view('view_category', $data);
	}

	public function info($bookId) {
		$book = $this->model_books->getBook($bookId);
		$data['book_info'] = $book;

		// Book Cover 
		$data['book_cover'] = getCover($book['id_document']);

		// Book Table of Content
		$contentTable = getTableContent($book['id_document']);
		$data['toc'] = $contentTable;

		//Get menu
        $data['template']['menu'] = createMenu();
        if($this->is_login())
        	$data['template']['user'] = $this->session->userdata('username');

		$this->load->view('view_book_info', $data);
	}


//============================================================================================
//===================================READ=READ=READ===========================================
//============================================================================================
	public function read($bookID, $chapter = null) {

		//From helper
		if( $chapter != '' && $chapter != 'no-more') 
		{
			// Get direct link to Folder Book
			$dir = base_url().'assets/resource/'.$bookID;
			$link_to_img = '';
			$link_chap = '';

			// Read book config file
			$temp = getBookOpf($dir);
			$xmlObject = $temp['object'];

			$arrChapId = array();
			$data['error'] = false;
			if ($xmlObject != -1) 
			{
				foreach ($xmlObject->spine->children() as $item) {				
						array_push($arrChapId, $item['idref']);
				}
				foreach ($xmlObject->manifest->children() as $item) 
				{
					if ((string)$item['id'] == $chapter) {
						if ($temp['isOEBPS']) {
							$link_chap = $dir.'/OEBPS/'.$item['href'];
							$link_to_img = $dir.'/OEPBS/';
						}
						else {
							$link_chap = $dir.'/'.$item['href'];
							$link_to_img = $dir.'/';
						}		
						break;
					}
					
				}

				if( !isset($link_chap) || $link_chap == '' ) {
					redirect(base_url().'book/info/'.$bookID);
					return;
				}

				if($this->is_login()) 
				{
					$user = $this->session->userdata('username');
					$this->load->model('model_books');
					$this->model_books->update_reading($user, $bookID, $chapter);

					$book = $this->model_books->getBook($bookID);
					$owner = $book['username'];

					if($user == $owner) $data['edittag'] = true;
				}
			}	

			$gettag = $this->input->get('tag');
			if(isset($gettag) && $gettag != '') {
				$this->load->model('model_tags');
				$data['tag'] = $this->model_tags->get_tag($gettag);
			}

			$current = array_search($chapter, $arrChapId);
			if ($current > 0) $data['prev_chapter'] = $arrChapId[$current - 1];
				else $data['prev_chapter'] = "no-more";
			if ($current < count($arrChapId) - 1 ) $data['next_chapter'] = $arrChapId[$current + 1];
				else $data['next_chapter'] = "no-more";

			$data['bookId'] = $bookID;
			$data['chapId'] = $chapter;
			$data['link_to_chapter'] = $link_chap;
			$data['content'] = $this->getContent($link_chap, $link_to_img, $bookID);

			// Get First Location
			$this->load->model('model_tags');
			$data['location_lv_1'] = $this->model_tags->getLocation('null');

			//Get menu
        	$data['template']['menu'] = createMenu();
        	if($this->is_login())
        		$data['template']['user'] = $this->session->userdata('username');

			$this->load->view('view_book_reading',$data);
		}
		else 
		{
			$this->info($bookID);
		}			
	}
	

	/**
	* ======================================================================================
	* ======================================================================================
	* Adding functions
	* ======================================================================================
	* ======================================================================================
	*/

	public function book_modify() {
		if(isset($_POST['link'])) 
		{
			$link = $_POST['link'];
			$strContent = $_POST['content'];

			$dom = new DOMDocument();
		   	$dom->load($link);

			$body = $dom->getElementsByTagName('body')->item(0);
			// echo $body->nodeName.'<br>';

			// Clear Content in real Pages
			while($body->firstChild) {
				$body->removeChild($body->firstChild);
			}

			$content = new DOMDocument();
			$content->loadHTML( '<?xml encoding="UTF-8">'. $strContent);
			$xpath= new DOMXPath($content);
			$content = $xpath->query('//html/body/*');

			foreach($content as $child) {
				$val = cloneNode($child, $dom);
				$body->appendChild($val);
			}

			$pos = strpos($link,'/assets');
			// echo $pos.' - '.substr($link, $pos).'<br>';

			$dir = './.'.substr($link, $pos);

			echo $dom->save($dir);
			// echo $body;
		}
	}

	public function add_tag() {

		$this->load->model('model_tags');
		if(isset($_POST['content'])) {
			$content = $_POST['content'];
			$book = $this->input->post('book');
			$chap = $this->input->post('chap');
			$location =  $this->input->post('location');
			$id_tag = 
				$this->model_tags->add_tag($content, $book, $chap, $location);
			
			echo 'success-'.$id_tag;
		}
		else echo 'no way';
	}

	// Load text content from xhtml files
	function getContent($link, $dir = null, $bookID) {
		@$raw = file_get_contents($link);
		if($raw) 
		{
			if($dir != null) {
				$html = str_replace('src="', 'src="'.$dir, $raw);
				$html = str_replace('../', '/', $html);
				$html = str_replace('xlink:href="', 'xlink:href="'.$dir, $html);


			} else $html = $raw;

			$doc = new DOMDocument();
			$doc->strictErrorChecking = FALSE;
			@$doc->loadHTML($html);
			$sxml = simplexml_import_dom($doc);
			
			$arr = getTableContent($bookID);
			$this->replace_href($sxml->body, $arr);

			return $sxml->body->children();
		}
		else return 'No file ';
	}

	function replace_href($xml, $toc) {
		foreach($xml->children() as $node) {
			if ($node->getName() == 'a') 
			{
				if(isset($node['href'])) 
				{
					$href = (string)$node['href'];
					$pos = strpos($href, 'html');
					$pointer = substr($href, $pos + 4);
					$sub_link = substr($href, 0, $pos);
					$href = $sub_link.'html';
					$node['href'] = $toc[1]['link'];

					foreach($toc as $item) 
					{
						if($href == $item['link']) {
							$node['href'] = $item['id'].$pointer;
							break;
						}
					}	
				}								
			}
			if($node->count() > 0)
				$this->replace_href($node, $toc);
		}
	}

/**
	* ======================================================================================
	* ======================================================================================
	* EDIT BOOK FUNCTION
	* ======================================================================================
	* ======================================================================================
	*/

	public function show_info_book($bookID){
		if($this->is_login()){
			$book = $this->model_books->getBook($bookID);

			$this->load->model('model_categories');
	        $data['cat'] = $this->model_categories->getMenu();

	        $this->load->model('model_user');
	        $data['loca'] = $this->model_user->get_loca();

	        $data['error'] = ' ';

			$data['template']['menu'] = createMenu();
	        if($this->is_login())
	            $data['template']['user'] = $this->session->userdata('username');

			// $bookID = $this->input->post('bookID');
			$this->load->model('model_books');
	        $data['info'] = $this->model_books->show_info($book['id_document']);
	        $this->load->view('view_book_edit', $data);
        }
        else
          	redirect(base_url()."book");
	}


	public function update_info_book($bookID){
		if($this->is_login())
		{
			$book = $this->model_books->getBook($bookID);

            $title = $this->input->post('title');
            $author = $this->input->post('author');
            $descript = $this->input->post('description');
            $cate = $this->input->post('category');
            $tags = $this->input->post('tags');
            $loca = $this->input->post('location');
            $user = $this->session->userdata('username');

            $this->load->model('model_books');
            $this->model_books->update_info( $book['id_document'], $title, $author, $descript, $cate, $tags, $loca);
            redirect(base_url()."book/info/".$book['id_document']);
        }
        else            
            redirect(base_url()."home");

        $data['template']['menu'] = createMenu();
        if($this->is_login())
            $data['template']['user'] = $this->session->userdata('username');
        $this->load->view('view_book_edit', $data);
        
	}

/**
	* ======================================================================================
	* ======================================================================================
	* DELETE BOOK FUNCTION
	* ======================================================================================
	* ======================================================================================
	*/
	public function delete_book($bookID){
		if($this->is_login()){

			$book = $this->model_books->getBook($bookID);
			$this->load->model('model_books');
            $this->model_books->delete_book( $book['id_document']);

            $path = './assets/resource/'.$book['id_document'];
            delete_files($path,TRUE);
            rmdir($path);

            redirect(base_url()."user");
		}
		else
			redirect(base_url()."home");

        $data['template']['menu'] = createMenu();
        if($this->is_login())
            $data['template']['user'] = $this->session->userdata('username');
	}

//=========================================================================
//=========================REMOVETAG=FUNCTION==============================
//=========================================================================
    public function remove_tag($tag_id) 
    {
        $this->load->model('model_tags');
        $tag = $this->model_tags->get_tag($tag_id);

        $this->model_tags->remove_tag($tag_id);

        $bookID = $tag['id_doc'];
        $chapid = $tag['id_chap'];

        // echo $bookID.' - '.$chapid.'<br>';

        $this->load->helper('bookaccess');
        if ($chapid != '') 
        {
            // Get direct link to Folder Book
            $dir = base_url().'assets/resource/'.$bookID;
            $link_to_img = '';
            $link_chap = '';

            // Read book config file
            $temp = getBookOpf($dir);
            $xmlObject = $temp['object'];

            $arrChapId = array();
            $data['error'] = false;
            if ($xmlObject != -1) 
            {
                foreach ($xmlObject->spine->children() as $item) {              
                        array_push($arrChapId, $item['idref']);
                }
                foreach ($xmlObject->manifest->children() as $item) 
                {
                    if ((string)$item['id'] == $chapid) {
                        if ($temp['isOEBPS']) {
                            $link_chap = $dir.'/OEBPS/'.$item['href'];
                            $link_to_img = $dir.'/OEPBS/';
                        }
                        else {
                            $link_chap = $dir.'/'.$item['href'];
                            $link_to_img = $dir.'/';
                        }       
                        break;
                    }
                    
                }

                if( !isset($link_chap) || $link_chap == '' ) {
                    redirect(base_url().'book/info/'.$bookID);
                    return;
                }
            }

            $current = array_search($chapid, $arrChapId);
            if ($current > 0) $data['prev_chapter'] = $arrChapId[$current - 1];
                else $data['prev_chapter'] = "no-more";
            if ($current < count($arrChapId) - 1 ) $data['next_chapter'] = $arrChapId[$current + 1];
                else $data['next_chapter'] = "no-more";

            $data['bookId'] = $bookID;
            $data['chapId'] = $chapid;
            $data['link_to_chapter'] = $link_chap;
            $data['content'] = $this->getContent($link_chap, $link_to_img, $bookID);

            // Get First Location
            $this->load->model('model_tags');
            $data['location_lv_1'] = $this->model_tags->getLocation('null');

            //Get menu
            $data['template']['menu'] = createMenu();
            if($this->is_login())
                $data['template']['user'] = $this->session->userdata('username');

            $data['action'] = 'removetag';
            $data['tagid'] = $tag_id;
            $this->load->view('view_book_reading',$data);
        }
    }
//======================================================================
//======================================================================
//======================================================================
    public function get_tag_content() {
    	$tagid = $this->input->post('tag');
    	$this->load->model('model_tags');
    	$tag = $this->model_tags->get_tag($tagid);

    	echo $tag['name_tags'];
    }

    public function ajax_child_location() {
    	$parent = $this->input->post('parent');
    	$this->load->model('model_tags');
    	$locations = $this->model_tags->getLocation($parent);
    	$str = '';
    	if(count($locations) > 0) {
    		$str .= '<select class="child" name="location1">';
    		$str .= '<option value="'.$parent.'">Không chọn</option>';
    		foreach ($locations as $local) {
    			$str .= '<option value="'. $local['id_location'] .'">';
    			$str .= $local['type_location'] .' '. $local['name_location'];
    			$str .= '</option>';
    		}
    		$str .= '</select>';

    		echo $str;
    	}
    	else echo '';
    }
}